package com.angel.thirds.components.keyboard
{
	//com.zguillez.events
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.KeyboardEvent;

import mx.core.UIComponent;

public class KeyboardDispatcher extends EventDispatcher {

		private static  var _instancia:KeyboardDispatcher;
		private static  var KEY_PRESS:String = "onKeyPress";
		//private var _clip:MovieClip;
		private var _clip:UIComponent;
		private var _funciones:Array;
		private var _teclas:Array;
		private var _tecla:uint;
		
		
		public function KeyboardDispatcher(s:Singleton,clip:UIComponent) {
			_clip = clip;
			_funciones = new Array();
			_teclas = new Array();
			_clip.stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
		}
		
		
		public static function getInstance(clip:UIComponent):KeyboardDispatcher {
			if (_instancia == null) {
				_instancia = new KeyboardDispatcher(new Singleton(),clip);
			}
			return _instancia;
		}
	
		public function addKey(n:uint, f:Function):void {
			_teclas.push(n);
			_funciones.push(f);
		}
		
		private function onKeyDown(tecla:KeyboardEvent):void {
			var total:uint = _teclas.length;
			if (total > 0) {
				for (var i:uint = 0; i < total ; i++) {
					if (tecla.keyCode == _teclas[i])
					{
					_funciones[i](tecla.keyCode);
					}
				}
			}
			_tecla = tecla.keyCode;
			dispatchEvent(new Event(KeyboardDispatcher.KEY_PRESS));
		}
		
		public function get tecla():uint {
			return _tecla;
		}

	}
}

class Singleton
{
}